package cn.edu.gzist.chapter07.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

// @Configuration
public class SecurityConfig4 {

    
	/**
	 * 两个用户
	 * user 拥有USER角色 hasRole("USER")
	 * admin 拥有ADMIN角色 hasRole("ROLE_ADMIN")
	 */
	// @Bean
	// public UserDetailsService userDetailsService() {
	// 	InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
	// 	inMemoryUserDetailsManager.createUser(User.withUsername("user").password("{noop}123456").roles("USER").build());
	// 	inMemoryUserDetailsManager.createUser(User.withUsername("admin").password("{noop}123456").roles("ROLE_ADMIN").build());
	// 	return inMemoryUserDetailsManager;
	// }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        // 所有路径需要认证
        httpSecurity.authorizeHttpRequests(authorize -> authorize.requestMatchers("/css/**","img/**","js/**").permitAll()
        .requestMatchers("/book/list").hasRole("USER")
        .requestMatchers("/book/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated());
        // Sercurity允许使用iframe加载网页
        httpSecurity.headers(header -> header.frameOptions(frame -> frame.disable()));
        // 关闭csrf安全，logout可以使用get方法
        httpSecurity.csrf(csrf -> csrf.disable());
        // 1. 使用基本方式
        // httpSecurity.httpBasic(Customizer.withDefaults());
        // 2. 使用默认页面方式
        // httpSecurity.formLogin(Customizer.withDefaults());
        // 3. 自定义登录页面
        httpSecurity.formLogin(form -> form.loginPage("/login").successForwardUrl("/main").permitAll());
        return httpSecurity.build(); 
    }
}
